<template>
    <div>
        <!-- <h4> {{id? '编辑文章':'新增文章'}} </h4> -->
        <a-card>
            <a-form-model
            :model="artInfo"
            ref="artInfoRef"
            :rules="artInfoRules"
            >
                <a-form-model-item label="文章标题" prop="title">
                    <a-input style="width:400px" v-model="artInfo.title"></a-input>
                </a-form-model-item>
                <a-form-model-item label="文章分类" prop="cid">
                    <a-select style="width:200px" v-model="artInfo.cid" placeholder="请选择分类" @click="cateChange">
                    <a-select-option v-for="item in cateList" :key="item.id" :value="item.id">{{item.name}} </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="文章描述" prop="desc">
                    <a-input type="textarea" v-model="artInfo.desc"></a-input>
                </a-form-model-item>
                <a-form-model-item label="文章缩略图" prop="img">
                    <a-upload
                      listType="picture"
                      :defaultFileList="fileList"
                      name="file"
                      :action="upUrl"
                      :headers="headers"
                      @change="upChange"
                    >
                        <a-button> <a-icon type="upload" /> 点击上传图片 </a-button>
                        <br>
                        <template v-if="id">
                            <img :src="artInfo.img" style="width:120px;height:100px" />
                        </template>
                    </a-upload>
                </a-form-model-item>
                <a-form-model-item label="文章内容" prop="content">
                    <!-- <a-input type="textarea" v-model="artInfo.content"></a-input> -->
                    <Editor type="textarea" v-model="artInfo.content"></Editor>
                </a-form-model-item>
                <a-form-model-item>
                    <a-button
                      type="danger"
                      style="margin-right:20px"
                      @click="artOk(artInfo.id)"
                    >{{artInfo.id? '更新':'提交'}}</a-button>
                    <a-button type="primary" @click="addCancel">取消</a-button>
                </a-form-model-item>
            </a-form-model>
        </a-card>
    </div>
</template>

<script>
// 导入组件
import { Url } from '../../plugin/http'
import Editor from '../editor/index'
export default {
  // 注册组件
  components: { Editor },
  props: ['id'],
  data () {
    return {
    // 文章字段内容
      artInfo: {
        id: 0,
        titie: '',
        cid: undefined,
        desc: '',
        content: '',
        img: ''
      },
      cateList: [],
      fileList: [],
      headers: {},
      upUrl: Url + '/upload',
      //   文章字段规则
      artInfoRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        cid: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
        desc: [
          { required: true, message: '请输入文章描述', trigger: 'blur' },
          { max: 120, message: '描述最多可写120个字符', trigger: 'change' }
        ],
        img: [{ required: true, message: '请选择文章缩略图', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  // 生命周期函数,页面渲染
  created () {
    this.getCateList()
    // 请求头获取token
    this.headers = { Authorization: `Bearer ${window.sessionStorage.getItem('token')}` }
    // 判断是否传递id，如果传递id就是编辑页面获取文章信息
    if (this.id) {
      this.getArtInfo(this.id)
    }
  },
  methods: {
    // 查询文章信息
    async getArtInfo (id) {
      const { data: res } = await this.$http.get(`article/info/${id}`)
      if (res.status !== 200) return this.$message.error(res.message)
      this.artInfo = res.data
      this.artInfo.id = res.data.ID
    },
    // 获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('cates')
      if (res.status !== 200) return this.$message.error(res.message)
      this.cateList = res.data
    },
    // 选择分类
    cateChange (value) {
      console.log(value)
      this.artInfo.cid = value
    },
    // 上传图片
    upChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success('图片上传成功')
        const imgUrl = info.file.response.url
        this.artInfo.img = imgUrl
      } else if (info.file.status === 'error') {
        this.$message.error('图片上传失败')
      }
    },
    // 提交&&更新文章
    artOk (id) {
      this.$refs.artInfoRef.validate(async (valid) => {
        if (id === 0) {
          const { data: res } = await this.$http.post('article/add', this.artInfo)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$router.push('/admin/artlist')
          this.$message.success('添加文章成功')
        } else {
          const { data: res } = await this.$http.put(`article/${id}`, this.artInfo)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$router.push('/admin/artlist')
          this.$message.success('更新文章成功')
        }
      })
    },
    // 取消
    addCancel () {
      this.$refs.artInfoRef.resetFields()
      this.$router.push('/admin/artlist')
    }
  }
}
</script>
